const classNames = require('classnames')
const { listParentBehavior, listItemBehavior, formItemBehavior } = require('../behaviors')
const _ = require('../utils')

_.create('picker', {
  properties: {
    label: String,
    mode: {
      type: String, // selector, multiSelector, time, date, region,
      value: 'Selector',
    },
    range: Array,
    rangeKey: { type: String, value: '' },
    customItem: { type: String, value: '' },
    level: { type: String, value: '' },
    start: { type: String, value: '' },
    end: { type: String, value: '' },
    fields: { type: String, value: 'day' },
    helperText: { type: String, value: '' },
    disabled: Boolean,
  },

  behaviors: ['wx://form-field', listItemBehavior, formItemBehavior],

  relations: {
    listParent: {
      type: 'parent',
      target: listParentBehavior,
    },
    '../form-validator/index': {
      type: 'ancestor',
    },
  },

  computed: {
    classes: function (data) {
      const { classPrefix, error } = data
      const classes = classNames(classPrefix, {
        [`${classPrefix}-error`]: error,
      })
      return classes
    },
  },

  observers: {
    value: function (value) {
      const { mode, range } = this.data

      let txt
      switch (mode) {
        case 'selector':
          txt = range[value]
          break
        case 'multiSelector':
          txt = range.map((item, index) => item[value[index]]).join(' ')
          break
        case 'region':
          txt = value.join(' ')
          break
        default:
          txt = value
          break
      }

      this.setData({ text: txt })
    },
  },

  methods: {
    onCancel() {},

    onDataChange(e) {
      const { value } = e.detail

      this.setData({ value })
      this.triggerEvent('change', e.detail)
    },

    onColumnChange(e) {
      this.triggerEvent('columnchange', e.detail)
    },
  },
})
